<script setup>
    import { ElMessage, ElMessageBox } from 'element-plus';
    import { ref, onMounted } from 'vue';
    import { useUserStore } from '@/store/user.js';
    import { updateUserInfo as upDateUserInfoApi } from '@/api/UserInfo.js';

    const userStore = useUserStore();
    const userInfo = ref({
        name: '',
        phone: '',
        email: '',
        avatarUrl: '',
        sex: '',
        birthday: null,
        introduce: '',
    });

    const rules = {
        phone:[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { pattern: /\d{11}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
        ],
    };

    const isHovering = ref(false); // 鼠标是否在头像上

    // 用户修改头像操作
    const updateUserAvatar = async (file) => {
        // TODO: 更新用户头像
        try {
            const base64AvatarUrl = await toBase64(file);
            console.log("base64AvatarUrl:", base64AvatarUrl);
            userInfo.value.avatarUrl = base64AvatarUrl;
            const response = await upDateUserInfoApi(userInfo.value);
            console.log("更新用户头像返回response:", response);
            if (response.data.code === 200){
                userStore.updateAvatar(userInfo.value.avatarUrl);
            } else {
                console.log(response);
            }
        } catch(error) {
            console.log(error);
        }
    } 

    // 将图片转为base64格式
    const toBase64 = file => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });

    // 处理头像上传
    const handleAvatarSuccess = async (response, file) => {
        try {
            // 模拟上传成功, 需要处理response和file
            // userInfo.value.avatarUrl = URL.createObjectURL(file.raw);
            await updateUserAvatar(file[Math.ceil(file.length-1)].raw);
            ElMessage({
                type: 'success',
                message: '头像上传成功',
            });
        } catch (error) {
            ElMessage.error('头像上传失败');
            console.log(error);
        }
    }

    // 对头像上传前的校验
    const beforeAvatarUpload = (file) => {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
            ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
            return false;
        }
        if (!isLt2M) {
            ElMessage.error('上传头像图片大小不能超过 2MB!');
            return false;
        }
        return isJPG && isLt2M;
    };

    //修改员工信息操作
    const upDateUserInfo = async () => {
        // TODO: 更新员工信息
        try {
            const response = await upDateUserInfoApi(userInfo.value);
            if (response.data.code === 200){
                userStore.setUserData(userInfo.value)
                console.log("修改后的userInfo:", userInfo.value)
                ElMessage({
                    type: 'success',
                    message: '修改已成功保存',
                });
            } else {
                ElMessage.error('修改保存失败');
                console.log("更新员工信息response:", response);
            }
        } catch(error) {
            console.log(error);
        }
    };

    // 存储原始信息
    const originalInfo = ref({ ...userInfo.value });

    // 保存信息按钮
    const saveInfo = async () => {
        try {
            // 如果没有任何修改，则提示
            if (JSON.stringify(userInfo.value) === JSON.stringify(originalInfo.value)) {
                ElMessage({
                    type: 'warning',
                    message: '没有修改任何信息',
                });
            } else { // 有修改
                ElMessageBox.confirm(
                    '你确定要保存更改吗？',
                    '确认保存',
                    {
                        confirmButtonText: '保存',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(() => {
                    originalInfo.value = { ...userInfo.value };
                    upDateUserInfo();
                }).catch(() => {
                    userInfo.value = { ...originalInfo.value };
                    ElMessage({
                        type: 'info',
                        message: '已取消更改',
                    });
                });
            }

        } catch (error) {
            console.log(error);
        }
    };

    // 取消编辑按钮
    const cancelInfo = () => {
        // 没有修改
        if (JSON.stringify(userInfo.value) === JSON.stringify(originalInfo.value)) {
            ElMessage({
                type: 'warning',
                message: '没有修改任何信息',
            });
            return;
        } else { // 有修改
            ElMessageBox.confirm(
                '你确定要取消更改吗？',
                '确认取消',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                userInfo.value = { ...originalInfo.value };
                ElMessage({
                    type: 'success',
                    message: '更改已取消',
                });
            }).catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消操作被终止',
                });
            });
        }
        
    };


    onMounted( async () => {
        console.log('===> Info.vue中的onMounted()方法执行了');
        try {
            userStore.loadUserFromToken();
            userInfo.value.name = userStore.username || '默认用户'; // 更新 userInfo
            userInfo.value.birthday = userStore.birthday;
            userInfo.value.avatarUrl = userStore.avatarUrl;
            userInfo.value.introduce = userStore.introduce;
            userInfo.value.sex = userStore.sex;
            userInfo.value.phone = userStore.phone;
            userInfo.value.email = userStore.email;

        } catch (error) {
            console.log(error);
        }
    });
</script>

<template>
    <div class="info-container">

        <el-card class="info-card" >
            
            <el-card class="info-card-header" shadow="always" >
                <el-row :model="userInfo">
                    <el-col :span="10" class="info-avatar" >
                        <el-upload
                            class="info-avatar-upload"
                            :show-file-list="false"
                            :auto-upload="false"
                            :on-change="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                        >
                            <el-avatar :size="130" 
                                :src="userInfo.avatarUrl || '/src/assets/img/1.jfif'" 
                                @mouseenter="isHovering = true" @mouseleave="isHovering = false"
                                style="margin-left: 40px;"
                            />
                        </el-upload>
                    </el-col>
                    
                    <el-col :span="14" class="info-name-col">
                        <el-text class="info-name">
                            {{ userInfo.name }}
                        </el-text>
                    </el-col>
                </el-row>
            </el-card>
            
            <el-card class="info-card-body" shadow="always" >
                <el-form :model="userInfo" :rules="rules" label-position=right size=large label-width="75px">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="电话号码">
                                <el-input v-model="userInfo.phone"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="邮箱">
                                <el-input v-model="userInfo.email"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="性别">
                                <el-radio-group v-model="userInfo.sex">
                                    <el-radio label="男">男</el-radio>
                                    <el-radio label="女">女</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="出生日期">
                                <el-date-picker
                                    v-model="userInfo.birthday"
                                    type="date"
                                    placeholder="birthday"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="个人简介">
                                <el-input type="textarea" v-model="userInfo.introduce"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="20">
                            <div class="info-button">
                                <el-button type="primary" @click="saveInfo">保存</el-button>
                            </div>
                            
                        </el-col>
                        <el-col :span="4">
                            <div class="info-button">
                                <el-button type="primary" @click="cancelInfo">取消</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </el-card>
    </div>
</template>

<style scoped>
    .info-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        width: 100%;
    }

    .info-card {
        display: flex;
        justify-content: center;
        align-items: top;
        width: 100%;
        height: 100%;
        background-color: #f0f0f0f7;
    }

    .info-card-header {
        justify-content: center;
        width: 700px;
    }

    .info-card-body {
        display: block;
        width: 700px;
        margin-top: 10px;
    }

    .info-name-col {
        align-content: center;
        justify-content: center;
    }

    .info-name {
        font-size: 40px;
        font-weight: bold;
        color: #3b3c51;
        margin-left: 150px;
    }

    .info-button {
        display: flex;
        justify-content: flex-end;
    }

    .info-avatar-uploader {
        position: relative;
        cursor: pointer;
        display: inline-block;
    }
</style>